package cn.wizzer.modules.controllers.platform.customer;

import cn.wizzer.common.annotation.SLog;
import cn.wizzer.common.base.Result;
import cn.wizzer.common.filter.PrivateFilter;
import cn.wizzer.common.page.DataTableColumn;
import cn.wizzer.common.page.DataTableOrder;
import cn.wizzer.modules.models.customer.Customer_documentary;
import cn.wizzer.modules.models.sys.Sys_user;
import cn.wizzer.modules.services.customer.CustomerDocumentaryService;
import cn.wizzer.modules.services.customer.CustomerService;
import cn.wizzer.modules.services.sys.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.List;

@IocBean
@At("/platform/customer/documentary")
@Filters({@By(type = PrivateFilter.class)})
public class CustomerDocumentaryController {
	private static final Log log = Logs.get();
	@Inject
	private CustomerDocumentaryService customerDocumentaryService;
	@Inject
	private CustomerService customerService;
	@Inject
	private SysUserService sysUserService;

	@At("")
	@Ok("beetl:/platform/customer/documentary/index.html")
	@RequiresAuthentication
	public void index() {

	}

	@At
	@Ok("json:full")
	@RequiresAuthentication
	public Object data(@Param("length") int length, @Param("start") int start, @Param("draw") int draw, @Param("::order") List<DataTableOrder> order, @Param("::columns") List<DataTableColumn> columns
	 ,@Param("at") String at,@Param("companyName") String companyName) {
		Cnd cnd = Cnd.NEW();
		Subject subject = SecurityUtils.getSubject();
		Sys_user user = (Sys_user) subject.getPrincipal();
		cnd.and("opBy","=",user.getId());

		String sql = "SELECT a.id,a.documentaryTime as documentaryTime,a.companyName as companyName,a.customerId as customerId,(select count(1) from customer_documentary " +
				"where customerId=a.customerId) as documentaryCount,a.state as state  FROM customer_documentary a WHERE 1=1  ";

		if (user!=null) {
			sql += " and a.opBy='"+user.getId()+"'";
		}
		if(!Strings.isBlank(at)){
			sql +=" and FROM_UNIXTIME(documentaryTime,'%Y-%m-%d')=STR_TO_DATE('"+at+"',\"%Y-%m-%d\")";
		}
		if(!Strings.isBlank(companyName)){
			sql += " and (a.companyName like '%" + companyName + "%') ";
		}
		sql +=" ORDER BY documentaryTime";
		return customerDocumentaryService.data(length, start, draw, Sqls.create(sql), Sqls.create(sql));
    }

	@At
	@Ok("json:full")
	@RequiresAuthentication
	public Object list(@Param("length") int length, @Param("start") int start, @Param("draw") int draw, @Param("::order") List<DataTableOrder> order, @Param("::columns") List<DataTableColumn> columns,@Param("customerId")String customerId) {
		Cnd cnd = Cnd.NEW();
		cnd.and("customerId","=",customerId);
		NutMap nutMap= customerDocumentaryService.data(length, start, draw, order, columns, cnd, null);
		if(!nutMap.isEmpty()){
			List<Customer_documentary> list=nutMap.getList("data",Customer_documentary.class);
			if(!list.isEmpty()) {
				list.forEach(p -> p.setNickName(sysUserService.fetch(p.getOpBy()).getNickname()));
			}
			nutMap.put("data",list);
		}
		return nutMap;
	}

    @At("/add/?")
    @Ok("beetl:/platform/customer/documentary/add.html")
    @RequiresAuthentication
    public Object add(@Param("customerId")String customerId) {
		return customerService.fetch(customerId);
    }

    @At
    @Ok("json")
    @SLog(tag = "新建Customer_documentary", msg = "")
    public Object addDo(@Param("..") Customer_documentary customerDocumentary,@Param("at") String at, HttpServletRequest req) {
		try {



			customerDocumentaryService.update(Chain.make("state",1),Cnd.where("customerId","=",customerDocumentary.getCustomerId()));

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			int documentaryTime = (int) (sdf.parse(at).getTime() / 1000);
			customerDocumentary.setDocumentaryTime(documentaryTime);
			customerDocumentaryService.insert(customerDocumentary);
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
    }

    @At("/edit/?")
    @Ok("beetl:/platform/customer/documentary/edit.html")
    @RequiresAuthentication
    public Object edit(String id) {
		return customerDocumentaryService.fetch(id);
    }

    @At
    @Ok("json")
    @SLog(tag = "修改Customer_documentary", msg = "ID:${args[0].id}")
    public Object editDo(@Param("..") Customer_documentary customerDocumentary, HttpServletRequest req) {
		try {
			customerDocumentary.setOpAt((int) (System.currentTimeMillis() / 1000));
			customerDocumentaryService.updateIgnoreNull(customerDocumentary);
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
    }


    @At({"/delete","/delete/?"})
    @Ok("json")
    @SLog(tag = "删除Customer_documentary", msg = "ID:${args[2].getAttribute('id')}")
    public Object delete(String id, @Param("ids") String[] ids ,HttpServletRequest req) {
		try {
			if(ids!=null&&ids.length>0){
				customerDocumentaryService.delete(ids);
    			req.setAttribute("id", org.apache.shiro.util.StringUtils.toString(ids));
			}else{
				customerDocumentaryService.delete(id);
    			req.setAttribute("id", id);
			}
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
    }


    @At("/detail/?")
    @Ok("beetl:/platform/customer/documentary/detail.html")
    @RequiresAuthentication
	public Object detail(String id) {
		if (!Strings.isBlank(id)) {
			return customerDocumentaryService.fetch(id);

		}
		return null;
    }

}
